What is p-memoize?
The p-memoize package is a promise-memoization library for JavaScript. It allows you to memoize the results of asynchronous functions, which can help improve performance by caching the results of expensive function calls and returning the cached result when the same inputs occur again.
What are p-memoize's main functionalities?
Basic Memoization
This feature allows you to memoize an asynchronous function. The first call to the function with a specific input will take the usual time, but subsequent calls with the same input will return the cached result immediately.
const pMemoize = require('p-memoize');
const expensiveFunction = async (input) => {
// Simulate an expensive operation
return new Promise(resolve => setTimeout(() => resolve(input * 2), 1000));
};
const memoizedFunction = pMemoize(expensiveFunction);
(async () => {
console.log(await memoizedFunction(2)); // Waits 1 second, logs 4
console.log(await memoizedFunction(2)); // Logs 4 immediately
})();
Custom Cache
This feature allows you to use a custom cache implementation. In this example, QuickLRU is used as the cache, which provides a least-recently-used (LRU) cache mechanism.
const pMemoize = require('p-memoize');
const QuickLRU = require('quick-lru');
const expensiveFunction = async (input) => {
// Simulate an expensive operation
return new Promise(resolve => setTimeout(() => resolve(input * 2), 1000));
};
const cache = new QuickLRU({ maxSize: 1000 });
const memoizedFunction = pMemoize(expensiveFunction, { cache });
(async () => {
console.log(await memoizedFunction(2)); // Waits 1 second, logs 4
console.log(await memoizedFunction(2)); // Logs 4 immediately
})();
Cache Key Customization
This feature allows you to customize the cache key. By default, the cache key is generated based on the function arguments, but you can provide a custom function to generate the cache key.
const pMemoize = require('p-memoize');
const expensiveFunction = async (input) => {
// Simulate an expensive operation
return new Promise(resolve => setTimeout(() => resolve(input * 2), 1000));
};
const memoizedFunction = pMemoize(expensiveFunction, {
cacheKey: ([input]) => `key-${input}`
});
(async () => {
console.log(await memoizedFunction(2)); // Waits 1 second, logs 4
console.log(await memoizedFunction(2)); // Logs 4 immediately
})();
Other packages similar to p-memoize
memoizee
memoizee is a general-purpose memoization library for JavaScript. It supports both synchronous and asynchronous functions, and offers a wide range of configuration options, including custom cache size, expiration, and more. Compared to p-memoize, memoizee is more feature-rich but also more complex to configure.
lru-cache
lru-cache is a simple and efficient LRU (Least Recently Used) cache library for JavaScript. While it does not provide memoization out of the box, it can be used in conjunction with custom memoization logic to achieve similar results. It is more focused on providing a robust caching mechanism rather than memoization specifically.
moize
moize is a high-performance memoization library for JavaScript that supports both synchronous and asynchronous functions. It offers a variety of configuration options, including custom cache keys, expiration, and more. moize is similar to p-memoize in terms of functionality but provides more advanced features and optimizations.
p-memoize
Memoize promise-returning & async functions
Useful for speeding up consecutive function calls by caching the result of calls with identical input.
By default, only the memoized function's first argument is considered via strict equality comparison. If you need to cache multiple arguments or cache object
s by value, have a look at alternative caching strategies below.
This package is similar to mem but with async-specific enhancements; in particular, it does not cache rejected promises by default (unless the cachePromiseRejection
option is set).
Install
$ npm install p-memoize
Usage
const pMemoize = require('p-memoize');
const got = require('got');
const memGot = pMemoize(got, {maxAge: 1000});
(async () => {
memGot('https://sindresorhus.com');
memGot('https://sindresorhus.com');
setTimeout(() => {
memGot('https://sindresorhus.com');
}, 2000);
})();
Caching strategy
See the Caching strategy for mem
.
API
pMemoize(fn, options?)
Returns a memoized version of the fn
function.
fn
Type: Function
Promise-returning or async function to be memoized.
options
Type: object
See the mem
options in addition to the below option.
cachePromiseRejection
Type: boolean
Default: false
Cache rejected promises.
pMemoize.clear(memoized)
Clear all cached data of a memoized function.
Will throw if passed a non-memoized function.
Related